//连接数据库
var mongoose = require("mongoose");
mongoose
  .connect("mongodb://127.0.0.1:27017/nav")
  .then((res) => {
    console.log("连接成功");
  })
  .catch((err) => {
    console.log("连接失败");
  });
const menuSchema = new mongoose.Schema({
  title: String,
  depth: Number,
  url: String,
  icon: String,
  pid: { type: mongoose.Types.ObjectId, ref: "Menu" },
});
const Menu = mongoose.model("Menu", menuSchema);
// const menu = new Menu({ title: "菜单4",depth:1})
// const menu = new Menu({ title: "菜单4",depth:2,pid:'689d88b7470e583e17856c1b'})
// menu.save()


function getfirst() {
  return new Promise((resolve, reject) => {
    Menu.find({ depth: 1 })
      .then((res) => {
        resolve(res);
      })
      .catch();
  });
}
function getsecond() {
  return new Promise((resolve, reject) => {
    getfirst().then((result) => {
      let data = JSON.parse(JSON.stringify(result))
      //遍历一级菜单，如果，得到一级菜单的id,用该id当做pid查找二级菜单，并把查找结果赋值给对应一级菜单的children
      for (let f = 0; f < data.length; f++) {
        Menu.find({ pid: data[f]._id.toString() }).then(res => {
          data[f].children = JSON.stringify(res)
          if (f === data.length - 1) {
            resolve(data)
          }
        }).catch();
      }
    });
  });
}
function getthird() {
  return new Promise((resolve, reject) => {
    getsecond().then(result => {
      //遍历二级菜单，
      let data = JSON.parse(JSON.stringify(result))
      for(let s=0;s<data.length;s++){
        data[s].children = JSON.parse(data[s].children);
        let datac = data[s].children;
        //如果一级菜单下有children内容(有数据)，遍历children内容，并把遍历查询得到的三级菜单赋值给对应的二级菜单的children
        if(datac.length>0){
          for(let t=0;t<datac.length;t++){
            Menu.find({ pid: datac[t]._id.toString()}).then(res=>{
              datac[t].children = JSON.stringify(res)
              if(s===(data.length-1) && t===(datac.length-1)){
                //console.log('遍历完成')
                resolve(data)
              }
            }).catch()

          }
        }else{
          //如果一级菜单下children没有数据，直接把一级菜单的数据resolve出去
          resolve(data)
        }
      }
    })
  })
}
// getsecond().then(data=>{
//   console.log('dd',data)
// })
getthird().then(data=>{
  //console.log('数据',data[0].children[0].children);
  console.log('数据',data);
})